import { createStore } from "vuex";
import request from "@/utils/request";
const store = createStore({
  state() {
    return {
      num: 100,
      stu: [
        // { name: "张三丰", score: 100 },
        // { name: "张翠山", score: 60 },
        // { name: "张无忌", score: 90 },
        // { name: "张三", score: 50 },
      ],
    };
  },
  getters: {
    //处理state数据，返回新数据，state变化时会触发getters的重新运算
    goodStu(state) {
      return state.stu.filter((item) => {
        return item.score >= 60;
      });
    },
  },
  mutations: {
    plus(state, m) {
      state.num += m;
    },
    minus(state) {
      state.num--;
    },
    addStuMut(state, stuObj) {
      state.stu.push(stuObj);
    },
    // 初始化设置从数据库拿到的数据
    initStuMut(state, stuArr) {
      state.stu = stuArr;
    },
  },
  actions: {
    addStuAction(context, stuObj) {
      // 向数据库录入数据
      request.post("classes/VueStu", stuObj).then((res) => {
        context.commit("addStuMut", stuObj); //向状态机存放数据
      });
    },
    getStuAction(context) {
      request.get("classes/VueStu").then((res) => {
        context.commit("initStuMut", res.data.results);
      });
    },
  },
});

export default store;
